package com.example.goods_admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.goods_admin.listener.DataListener;
import com.example.goods_admin.common.Result;
import com.example.goods_admin.entity.Book;
import com.example.goods_admin.mapper.BookMapper;
import com.example.goods_admin.service.BookService;
import com.example.goods_admin.utils.EasyExcelUtil;
import com.google.common.collect.Lists;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    /**
     * 每隔1000条存储数据库，然后清理list ，方便内存回收
     */
    //TODO 定义变量
    private static final int BATCH_COUNT = 1000;
    @Autowired
    BookMapper bookMapper;

    @Override
    public Result uploadExcel(MultipartFile file) {
        try {
            // 获取输入流，这里需要自行实现获取输入流的逻辑
            InputStream inputStream = file.getInputStream();

            List<Book> list = EasyExcelUtil.read(inputStream, Book.class);

            List<List<Book>> partition = Lists.partition(list, BATCH_COUNT);

            for (List<Book> bookList : partition) {
                bookMapper.batchInsertBook(bookList);
            }
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            return Result.failed("导入失败");
        }
        return Result.succeed("导入成功");
    }

    @Override
    public void downloadExcel(HttpServletResponse httpServletResponse) throws IOException {
        //1、查询数据库数据
        List<Book> list =bookMapper.selectAllBook();

        //导出
        EasyExcelUtil.download(httpServletResponse,list,Book.class, "喜欢看得书籍","书籍");
    }
}
